<?php

namespace app\common\model;
use x\Xbase;
class OrderCart extends Xbase
{
    /**
     * 添加更新删除购物车
     * @param [type] $user_id        [用户id]
     * @param [type] $goods_price_id [产品id]
     * @param [type] $nums           [数量]
     */
    public function edit($user_id,$goods_price_id,$nums){
        $info = $this->db->find("goods_price",$goods_price_id);
        if($info["stock"] < $nums)
            return $this->setError("库存不足");
        $rs = $this->db->query('select * from order_cart where user_id = ? and goods_price_id = ?',[$user_id,$info['id']],1);
        if($rs){
            if ($nums==0) {
                $this->db->delete('order_cart',$rs['id']);
            }else{
                $data = [
                    'nums'=>$nums,
                    'id'=>$rs['id']
                ];
                $this->db->update('order_cart',$data);
            }
        }else{
            if($nums != 0){
                $data = [
                    'user_id'=>$user_id,
                    'goods_id'=>$info['goods_id'],
                    'goods_price_id'=>$info['id'],
                    'nums'=>$nums,
                    'create_time'=>time(),
                ];
                $this->db->insert('order_cart',$data);
            }
        }
        return true;
    }

    /**
     * 我的购物车
     * @param  [type] $user_id [description]
     * @param  [type] $goods_type [description]
     * @return [type]          [description]
     */
    public function lists($user_id){
        $field = [
            'a.id',
            'b.id as goods_price_id',
            'c.id as goods_id',
            'c.title as goods_name',
            'b.title as goods_spec_name',
            'b.price',
            'c.point',
            'c.postage',
            'c.pic',
            'a.nums',
            'd.name as shop_name',
            'c.market_price',

        ];
        $field = implode(",", $field);
        $rs = $this->db->query("
        select
            {$field}
        from
            order_cart as a
        inner join
            goods_price b on a.goods_price_id = b.id
        left join
            goods c on b.goods_id=c.id
        left join
            shop d on d.id = b.shop_id
        where a.user_id = ? ",[$user_id]);
        return $rs;
    }
}
